
//package java_cup.runtime;

//import java.lang.reflect.Field;
//import java.util.LinkedList;
//import java.util.List;
//import java.util.Stack;

//import java_cup.runtime.ComplexSymbolFactory.ComplexSymbol;



using System.Text;
using static ComplexSymbolFactory;

/**
 * This class : a skeleton table driven LR CUPParser. In general, LR
 * parsers are a form of bottom up Shift-reduce parsers. Shift-reduce parsers
 * act by shifting input onto a parse stack until the Symbols matching the _right
 * hand side of a production appear on the Peek of the stack. Once this occurs, a
 * reduce is performed. This involves removing the Symbols corresponding to the
 * _right hand side of the production (the so called "handle") and replacing them
 * with the non-terminal from the _left hand side of the production.
 * <p>
 *
 * To control the decision of whether to Shift or reduce at any given point, the
 * CUPParser uses a state machine (the "viable prefix recognition machine" built by
 * the CUPParser generator). The current state of the machine is placed on Peek of
 * the parse stack (stored as part of a TheSymbolDraft object representing a terminal or
 * non terminal). The parse actionPart table is consulted (using the current state
 * and the current lookahead TheSymbolDraft as indexes) to determine whether to Shift or
 * to reduce. When the CUPParser shifts, it changes to a new state by pushing a new
 * TheSymbolDraft (containing a new state) onto the stack. When the CUPParser reduces, it
 * pops the handle (_right hand side of a production) off the stack. This leaves
 * the CUPParser in the state it was in before any of those Symbols were matched.
 * Next the reduce-goto table is consulted (using the new state and current
 * lookahead TheSymbolDraft as indexes) to determine a new state to go to. The CUPParser
 * then shifts to this goto state by pushing the _left hand side TheSymbolDraft of the
 * production (also containing the new state) onto the stack.
 * <p>
 *
 * This class actually provides four LR parsers. The methods parse() and
 * debug_parse() provide two versions of the main CUPParser (the only difference
 * being that debug_parse() emits debugging trace messages as it parses). In
 * addition to these main parsers, the error recovery mechanism uses two more.
 * One of these is used to simulate "parsing ahead" in the input without
 * carrying @out actions (to verify that a potential error recovery has worked),
 * and the other is used to parse through buffered "parse ahead" input in order
 * to execute AllVns actions and re-synchronize the actual CUPParser configuration.
 * <p>
 *
 * This is an abstract class which is normally filled @out by a subclass
 * generated by the JavaCup CUPParser generator. In addition to supplying the
 * actual parse tables, generated code also supplies methods which invoke
 * various pieces of user supplied code, provide access to certain special
 * Symbols (e.g., EOF and error), etc. Specifically, the following abstract
 * methods are normally supplied by generated code: <dl compact>
 * <dt>short[][] production_table()
 * <dd>Provides a reference to the production table (indicating the index of the
 * _left hand side non terminal and the length of the _right hand side for each
 * production in the grammar).
 * <dt>short[][] action_table()
 * <dd>Provides a reference to the parse actionPart table.
 * <dt>short[][] reduce_table()
 * <dd>Provides a reference to the reduce-goto table.
 * <dt>int start_state()
 * <dd>Indicates the index of the start state.
 * <dt>int firstProduction()
 * <dd>Indicates the index of the starting production.
 * <dt>int EOF_sym()
 * <dd>Indicates the index of the EOF TheSymbolDraft.
 * <dt>int error_sym()
 * <dd>Indicates the index of the error TheSymbolDraft.
 * <dt>TheSymbolDraft do_action()
 * <dd>Executes a piece of user supplied actionPart code. This always comes at the
 * point of a reduce in the parse, so this code also allocates and fills in the
 * _left hand side non terminal TheSymbolDraft object that is to be pushed onto the stack
 * for the reduce.
 * <dt>void init_actions()
 * <dd>Code to initialize a special object that encapsulates user supplied
 * actions (this object is used by do_action() to actually carry @out the
 * actions).
 * </dl>
 * 
 * In addition to these routines that <i>must</i> be supplied by the generated
 * subclass there are also a series of routines that <i>may</i> be supplied.
 * These include:
 * <dl>
 * <dt>TheSymbolDraft scan()
 * <dd>Used to get the next input TheSymbolDraft from the scanner.
 * <dt>Scanner getScanner()
 * <dd>Used to provide a scanner for the default implementation of scan().
 * <dt>int error_sync_size()
 * <dd>This determines how many Symbols past the point of an error must be
 * parsed without error in order to consider a recovery to be valid. This
 * defaults to 3. Values less than 2 are not recommended.
 * <dt>void report_error(String message, Object info)
 * <dd>This method is called to report an error. The default implementation
 * simply prints a message to System.err and where the error occurred. This
 * method is often replaced in order to provide a more sophisticated error
 * reporting mechanism.
 * <dt>void report_fatal_error(String message, Object info)
 * <dd>This method is called when a fatal error that cannot be recovered from is
 * encountered. In the default implementation, it calls report_error() to emit a
 * message, then throws an exception.
 * <dt>void syntax_error(TheSymbolDraft cur_token)
 * <dd>This method is called as soon as syntax error is detected (but before
 * recovery is attempted). In the default implementation it invokes:
 * report_error("Syntax error", null);
 * <dt>void unrecovered_syntax_error(TheSymbolDraft cur_token)
 * <dd>This method is called if syntax error recovery fails. In the default
 * implementation it invokes:<br>
 * report_fatal_error("Couldn't repair and continue parse", null);
 * </dl>
 *
 * @see java_cup.runtime.TheSymbolDraft
 * @see java_cup.runtime.TheSymbolDraft
 * @see java_cup.runtime.virtual_parse_stack
 * @version last updated: 7/3/96
 * @author Frank Flannery
 */
public abstract class LRParser {
    /*-----------------------------------------------------------*/
    /*--- Constructor(s) ----------------------------------------*/
    /*-----------------------------------------------------------*/

    /**
     * Simple constructor. deprecated; The use of a SymbolFactory, e.g.
     * Complexsymbolfactory is advised
     */
    /*@Deprecated*/
    public LRParser() : this(new DefaultSymbolFactory()) {
    }

    /**
     * Simple constructor.
     */
    public LRParser(SymbolFactory fac) {
        symbolFactory = fac;
    }

    /**
     * Constructor that sets the default scanner. [CSA/davidm] deprecated; The use
     * of a SymbolFactory, e.g. Complexsymbolfactory is advised
     */
    /*@Deprecated*/
    public LRParser(Scanner s) : this(s, new DefaultSymbolFactory()) {
        // TUM 20060327 old cup v10 Symbols as default
    }

    /**
     * Constructor that sets the default scanner and a SymbolFactory
     */
    public LRParser(Scanner s, SymbolFactory symfac)
        // in case default constructor someday does something
        : this() {
        symbolFactory = symfac;
        setScanner(s);
    }

    public SymbolFactory symbolFactory;

    /**
     * Whenever creation of a new TheSymbolDraft is necessary, one should use this factory.
     */
    public SymbolFactory SymbolFactory => symbolFactory;
    /*-----------------------------------------------------------*/
    /*--- (Access to) Static (Class) Variables ------------------*/
    /*-----------------------------------------------------------*/

    /**
     * The default Count of Symbols after an error we much match to consider it
     * recovered from.
     */
    public const int _errorSyncSize = 3;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * The Count of Symbols after an error we much match to consider it recovered
     * from.
     */
    public int errorSyncSize => _errorSyncSize;

    /*-----------------------------------------------------------*/
    /*--- (Access to) Instance Variables ------------------------*/
    /*-----------------------------------------------------------*/

    /**
     * Table of production information (supplied by generated subclass). This table
     * contains one entry per production and is indexed by the negative-encoded
     * values (reduce actions) in the action_table. Each entry has two parts, the
     * index of the non-terminal on the _left hand side of the production, and the
     * Count of Symbols on the _right hand side.
     */
    public abstract short[][] productionTable();

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * The actionPart table (supplied by generated subclass). This table is indexed by
     * state and terminal Count indicating what actionPart is to be taken when the
     * CUPParser is in the given state (i.e., the given state is on Peek of the stack)
     * and the given terminal is next on the input. States are indexed using the
     * first dimension, however, the entries for a given state are compacted and
     * stored in adjacent index, value pairs which are searched for rather than
     * accessed directly (see get_action()). The actions stored in the table will be
     * either shifts, reduces, or errors. Shifts are encoded as positive values (one
     * greater than the state shifted to). Reduces are encoded as negative values
     * (one less than the production reduced by). ExceptionXml entries are denoted by zero.
     * 
     * @see java_cup.runtime.LRParser#get_action
     */
    public abstract short[][] actionTable();

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * The reduce-goto table (supplied by generated subclass). This table is indexed
     * by state and non-terminal Count and contains state numbers. States are
     * indexed using the first dimension, however, the entries for a given state are
     * compacted and stored in adjacent index, value pairs which are searched for
     * rather than accessed directly (see get_reduce()). When a reduce occurs, the
     * handle (corresponding to the RHS of the matched production) is popped off the
     * stack. The new Peek of stack indicates a state. This table is then indexed by
     * that state and the LHS of the reducing production to indicate where to
     * "Shift" to.
     *
     * @see java_cup.runtime.LRParser#get_reduce
     */
    public abstract short[][] reduceTable();

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** The index of the start state (supplied by generated subclass). */
    public abstract int startState();

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** The index of the start production (supplied by generated subclass). */
    public abstract int startProduction();

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * The index of the end of file terminal TheSymbolDraft (supplied by generated
     * subclass).
     */
    public abstract int EOFSym();

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** The index of the special error TheSymbolDraft (supplied by generated subclass). */
    public abstract int errorSym();

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** Internal flag to indicate when CUPParser should quit. */
    public bool _done_parsing = false;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * This method is called to indicate that the CUPParser should quit. This is
     * normally called by an accept actionPart, but can be used to cancel parsing early
     * in other circumstances if desired.
     */
    public void doneParsing() => _done_parsing = true;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */
    /*
     * Global parse state shared by parse(), error recovery, and debugging routines
     */
    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** Indication of the index for Peek of stack (for use by actions). */
    public int tos;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** The current lookahead TheSymbolDraft. */
    public Node cur_token;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** The parse stack itself. */
    public Stack<Node> stack = new();

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** Direct reference to the production table. */
    public short[][] production_tab;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** Direct reference to the actionPart table. */
    public short[][] action_tab;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** Direct reference to the reduce-goto table. */
    public short[][] reduce_tab;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * This is the scanner object used by the default implementation of scan() to
     * get Symbols. To avoid name conflicts with existing code, this field is
     * public. [CSA/davidm]
     */
    public Scanner _scanner;

    /**
     * Simple accessor method to set the default scanner.
     */
    public void setScanner(Scanner s) {
        _scanner = s;
    }

    /**
     * Simple accessor method to get the default scanner.
     */
    public Scanner Scanner => _scanner;

    /*-----------------------------------------------------------*/
    /*--- General Methods ---------------------------------------*/
    /*-----------------------------------------------------------*/

    /**
     * Perform a bit of user supplied actionPart code (supplied by generated subclass).
     * Actions are indexed by an internal actionPart Count assigned at CUPParser
     * generation time.
     *
     * @param act_num the internal index of the actionPart to be performed.
     * @param CUPParser  the CUPParser object we are acting for.
     * @param stack   the parse stack of that object.
     * @param Peek     the index of the Peek element of the parse stack.
     */
    public abstract Node doAction(int actNum, LRParser parser, Stack<Node> stack, int top)
        /*throws java.lang.ExceptionXml*/;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * User code for initialization inside the CUPParser. Typically this initializes
     * the scanner. This is called before the CUPParser requests the first TheSymbolDraft. Here
     * this is just a placeholder for subclasses that might need this and we perform
     * no actionPart. This method is normally overridden by the generated code using
     * this contents of the "init with" clause as its body.
     */
    public void userInit() /*throws java.lang.ExceptionXml*/ {
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Initialize the actionPart object. This is called before the CUPParser does any parse
     * actions. This is filled in by generated code to create an object that
     * encapsulates AllVns actionPart code.
     */
    public abstract void initActions() /*throws java.lang.ExceptionXml*/;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Get the next TheSymbolDraft from the input (supplied by generated subclass). Once end
     * of file has been reached, AllVns subsequent calls to scan should return an EOF
     * TheSymbolDraft (which is TheSymbolDraft Count 0). By default this method returns
     * getScanner().next_token(); this implementation can be overriden by the
     * generated CUPParser using the code declared in the "scan with" clause. Do not
     * recycle objects; every call to scan() should return a fresh object.
     */
    public Node scan() /*throws java.lang.ExceptionXml*/ {
        Node sym = Scanner.nextToken();
        return (sym != null) ? sym : SymbolFactory.newSymbol("END_OF_FILE", EOFSym());
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Report a fatal error. This method takes a message string and an additional
     * object (to be used by specializations implemented in subclasses). Here in the
     * base class a very simple implementation is provided which reports the error
     * then throws an exception.
     *
     * @param message an error message.
     * @param info    an extra object reserved for use by specialized subclasses.
     */
    public void reportFatalError(String message, Object info) /*throws java.lang.ExceptionXml*/ {
        /* stop parsing (not really necessary since we throw an exception, but) */
        doneParsing();

        /* use the normal error message reporting to put @out the message */
        reportError(message, info);

        /* throw an exception */
        throw new Exception("Can't recover from previous error(s)");
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Report a non fatal error (or warning). This method takes a message string and
     * an additional object (to be used by specializations implemented in
     * subclasses). Here in the base class a very simple implementation is provided
     * which simply prints the message to System.err.
     *
     * @param message an error message.
     * @param info    an extra object reserved for use by specialized subclasses.
     */
    public void reportError(String message, Object info) {
        if (info is ComplexSymbol) {
            ComplexSymbol cs = (ComplexSymbol)info;
            System/*error*/.Console.WriteLine(message + " for input SymbolDraft \"" + cs.Name + "\" spanning from " + cs.Left + " to "
                + cs.Right);
            return;
        }

        System/*error*/.Console.Write(message);
        //System.err.flush();
        if (info is Node)
            if (((Node)info)._left != -1)
                System/*error*/.Console.WriteLine(" at character " + ((Node)info)._left + " of input");
            else
                System/*error*/.Console.WriteLine("");
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * This method is called when a syntax error has been detected and recovery is
     * about to be invoked. Here in the base class we just emit a "Syntax error"
     * error message.
     *
     * @param cur_token the current lookahead TheSymbolDraft.
     */
    public void syntaxError(Node curToken) {
        reportError("Syntax error", curToken);
        reportExpectedTokenIds();
    }

    /**
     * We need this Method in order to resolve names for SymbolDraft IDs
     * 
     * @return the class that keeps AllVns the EmitSymbols
     */
    public object getSymbolContainer() {
        return null;
    }

    public void reportExpectedTokenIds() {
        List<int> ids = expectedTokenIds();
        LinkedList<String> list = new();
        foreach (int expected in ids) {
            list.AddLast(symblNameFromId(expected));
        }
        System.Console.WriteLine("instead expected token classes are " + list);
    }

    /**
     * Translates numerical SymbolDraft ids to the (non)terminal names from the spec
     * 
     * @param internal id for (non)terminal
     * @return (non)terminal name as string
     */
    public String symblNameFromId(int id) {
        //Field[] fields = getSymbolContainer().getFields();
        //foreach (Field f in fields) {
        //    try {
        //        if (f.getInt(null) == id)
        //            return f.getName();
        //    }
        //    catch (IllegalArgumentException e) {
        //        // Console.WriteLine(e);
        //    }
        //    catch (IllegalAccessException e) {
        //        // Console.WriteLine(e);
        //    }
        //}
        return "invalid SymbolDraft id";
    }

    /**
     * Return the expected SymbolDraft during this state of state of the CUPParser
     * 
     * @return list of integer (non)temrinal ids
     */
    public List<int> expectedTokenIds() {
        List<int> ret = new();
        int parse_state = stack.Peek().parse_state;
        short[] row = action_tab[parse_state];
        for (int i = 0; i < row.Length; i += 2) {
            if (row[i] == -1)
                continue;
            if (!validateExpectedSymbol(row[i]))
                continue;
            ret.Add(row[i]);
        }
        return ret;
    }

    public bool validateExpectedSymbol(int id) {
        short lhs, rhs_size;
        int act;
        try {
            VirtualParseStack vstack = new VirtualParseStack(stack);
            /* parse until we fail or get past the lookahead input */
            for (; ; ) {
                /* look up the actionPart from the current state (on Peek of stack) */
                act = getAction(vstack.Peek(), id);

                /* if its an error, we fail */
                if (act == 0)
                    return false;

                /* > 0 encodes a Shift */
                if (act > 0) {
                    /* Push the new state on the stack */
                    vstack.Push(act - 1);

                    /* advance simulated input, if we run off the end, we are done */
                    if (!advanceLookahead())
                        return true;
                }
                /* < 0 encodes a reduce */
                else {
                    /* if this is a reduce with the start production we are done */
                    if ((-act) - 1 == startProduction())
                        return true;

                    /* get the lhs TheSymbolDraft and the rhs Count */
                    lhs = production_tab[(-act) - 1][0];
                    rhs_size = production_tab[(-act) - 1][1];
                    /* Pop handle off the stack */
                    for (int i = 0; i < rhs_size; i++)
                        vstack.Pop();

                    vstack.Push(getReduce(vstack.Peek(), lhs));
                }
            }

        }
        catch (Exception e) {
            Console.WriteLine(e);
        }
        return true;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * This method is called if it is determined that syntax error recovery has been
     * unsuccessful. Here in the base class we report a fatal error.
     *
     * @param cur_token the current lookahead TheSymbolDraft.
     */
    public void unrecoveredSyntaxError(Node curToken) /*throws java.lang.ExceptionXml*/ {
        reportFatalError("Couldn't repair and continue parse", curToken);
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Fetch an actionPart from the actionPart table. The table is broken up into rows, one
     * per state (rows are indexed directly by state Count). Within each row, a
     * list of index, value pairs are given (as sequential entries in the table),
     * and the list is terminated by a default entry (denoted with a TheSymbolDraft index of
     * -1). To find the proper entry in a row we do a linear or binary search
     * (depending on the Count of the row).
     *
     * @param state the state index of the actionPart being accessed.
     * @param symbolCount   the TheSymbolDraft index of the actionPart being accessed.
     */
    public short getAction(int state, int sym) {
        short tag;
        int first, last, probe;
        short[] row = action_tab[state];

        /* linear search if we are < 10 entries */
        if (row.Length < 20)
            for (probe = 0; probe < row.Length; probe++) {
                /* is this entry labeled with our TheSymbolDraft or the default? */
                tag = row[probe++];
                if (tag == sym || tag == -1) {
                    /* return the next entry */
                    return row[probe];
                }
            }
        /* otherwise binary search */
        else {
            first = 0;
            last = (row.Length - 1) / 2 - 1; /* leave @out trailing default entry */
            while (first <= last) {
                probe = (first + last) / 2;
                if (sym == row[probe * 2])
                    return row[probe * 2 + 1];
                else if (sym > row[probe * 2])
                    first = probe + 1;
                else
                    last = probe - 1;
            }

            /* not found, use the default at the end */
            return row[row.Length - 1];
        }

        /*
         * shouldn't happened, but if we run off the end we return the default (error ==
         * 0)
         */
        return 0;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Fetch a state from the reduce-goto table. The table is broken up into rows,
     * one per state (rows are indexed directly by state Count). Within each row, a
     * list of index, value pairs are given (as sequential entries in the table),
     * and the list is terminated by a default entry (denoted with a TheSymbolDraft index of
     * -1). To find the proper entry in a row we do a linear search.
     *
     * @param state the state index of the entry being accessed.
     * @param symbolCount   the TheSymbolDraft index of the entry being accessed.
     */
    public short getReduce(int state, int sym) {
        short tag;
        short[] row = reduce_tab[state];

        /* if we have a null row we go with the default */
        if (row == null)
            return -1;

        for (int probe = 0; probe < row.Length; probe++) {
            /* is this entry labeled with our TheSymbolDraft or the default? */
            tag = row[probe++];
            if (tag == sym || tag == -1) {
                /* return the next entry */
                return row[probe];
            }
        }
        /* if we run off the end we return the default (error == -1) */
        return -1;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * This method provides the main parsing routine. It returns only when
     * done_parsing() has been called (typically because the CUPParser has accepted, or
     * a fatal error has been reported). See the header documentation for the class
     * regarding how Shift/reduce parsers operate and how the various tables are
     * used.
     */
    public Node parse() /*throws java.lang.ExceptionXml*/ {
        /* the current actionPart code */
        int act;

        /* the TheSymbolDraft/stack element returned by a reduce */
        Node lhs_sym = null;

        /* information about production being reduced with */
        short handle_size, lhs_sym_num;

        /* set up direct reference to tables to drive the CUPParser */

        production_tab = productionTable();
        action_tab = actionTable();
        reduce_tab = reduceTable();

        /* initialize the actionPart encapsulation object */
        initActions();

        /* do user initialization */
        userInit();

        /* get the first token */
        cur_token = scan();

        /* Push dummy TheSymbolDraft with start state to get us underway */
        stack.Clear();
        stack.Push(SymbolFactory.startSymbol("START", 0, startState()));
        tos = 0;

        /* continue until we are told to stop */
        for (_done_parsing = false; !_done_parsing;) {
            /* Check current token for freshness. */
            if (cur_token.used_by_parser)
                throw new Exception("TheSymbolDraft recycling detected (fix your scanner).");

            /* current state is always on the Peek of the stack */

            /* look up actionPart @out of the current state with the current input */
            act = getAction(stack.Peek().parse_state, cur_token.symbolCount);

            /* decode the actionPart -- > 0 encodes Shift */
            if (act > 0) {
                /* Shift to the encoded state by pushing it on the stack */
                cur_token.parse_state = act - 1;
                cur_token.used_by_parser = true;
                stack.Push(cur_token);
                tos++;

                /* advance to the next TheSymbolDraft */
                cur_token = scan();
            }
            /* if its less than zero, then it encodes a reduce actionPart */
            else if (act < 0) {
                /* perform the actionPart for the reduce */
                lhs_sym = doAction((-act) - 1, this, stack, tos);

                /* look up information about the production */
                lhs_sym_num = production_tab[(-act) - 1][0];
                handle_size = production_tab[(-act) - 1][1];

                /* Pop the handle off the stack */
                for (int i = 0; i < handle_size; i++) {
                    stack.Pop();
                    tos--;
                }

                /* look up the state to go to from the one popped back to */
                act = getReduce(stack.Peek().parse_state, lhs_sym_num);

                /* Shift to that state */
                lhs_sym.parse_state = act;
                lhs_sym.used_by_parser = true;
                stack.Push(lhs_sym);
                tos++;
            }
            /* finally if the entry is zero, we have an error */
            else if (act == 0) {
                /* call user syntax error reporting routine */
                syntaxError(cur_token);

                /* try to error recover */
                if (!errorRecovery(false)) {
                    /* if that fails give up with a fatal syntax error */
                    unrecoveredSyntaxError(cur_token);

                    /* just in case that wasn't fatal enough, end parse */
                    doneParsing();
                }
                else {
                    lhs_sym = stack.Peek();
                }
            }
        }
        return lhs_sym;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Write a debugging message to System.err for the debugging version of the
     * CUPParser.
     *
     * @param mess the text of the debugging message.
     */
    public void debugMessage(String mess) {
        System/*error*/.Console.WriteLine(mess);
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** Dump the parse stack for debugging purposes. */
    public void dumpStack() {
        if (stack == null) {
            debugMessage("# Stack dump requested, but stack is null");
            return;
        }

        debugMessage("============ Parse Stack Dump ============");

        /* dump the stack */
        for (int i = 0; i < stack.Count; i++) {
            debugMessage("TheSymbolDraft: " + stack.ElementAt(i).symbolCount + " State: " + stack.ElementAt(i).parse_state);
        }
        debugMessage("==========================================");
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Do debug output for a reduce.
     *
     * @param prod_num the production we are reducing with.
     * @param nt_num   the index of the LHS non terminal.
     * @param rhs_size the Count of the RHS.
     */
    public void debugReduce(int prodNum, int ntNum, int rhsSize) {
        debugMessage("# Reduce with prod #" + prodNum + " [NT=" + ntNum + ", " + "SZ=" + rhsSize + "]");
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Do debug output for Shift.
     *
     * @param shift_tkn the TheSymbolDraft being shifted onto the stack.
     */
    public void debugShift(Node shiftTkn) {
        debugMessage("# Shift under term #" + shiftTkn.symbolCount + " to state #" + shiftTkn.parse_state);
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Do debug output for stack state. [CSA]
     */
    public void debugStack() {
        var sb = new StringBuilder("## STACK:");
        for (int i = 0; i < stack.Count; i++) {
            Node s = stack.ElementAt(i);
            sb.Append(" <state " + s.parse_state + ", symbolCount " + s.symbolCount + ">");
            if ((i % 3) == 2 || (i == (stack.Count - 1))) {
                debugMessage(sb.ToString());
                sb = new StringBuilder("         ");
            }
        }
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Perform a parse with debugging output. This does exactly the same things as
     * parse(), except that it calls debug_shift() and debug_reduce() when Shift and
     * reduce moves are taken by the CUPParser and produces various other debugging
     * messages.
     */
    public Node debugParse() /*throws java.lang.ExceptionXml*/ {
        /* the current actionPart code */
        int act;

        /* the TheSymbolDraft/stack element returned by a reduce */
        Node lhs_sym = null;

        /* information about production being reduced with */
        short handle_size, lhs_sym_num;

        /* set up direct reference to tables to drive the CUPParser */
        production_tab = productionTable();
        action_tab = actionTable();
        reduce_tab = reduceTable();

        debugMessage("# Initializing CUPParser");

        /* initialize the actionPart encapsulation object */
        initActions();

        /* do user initialization */
        userInit();

        /* the current TheSymbolDraft */
        cur_token = scan();

        debugMessage("# Current TheSymbolDraft is #" + cur_token.symbolCount);

        /* Push dummy TheSymbolDraft with start state to get us underway */
        stack.Clear();
        stack.Push(SymbolFactory.startSymbol("START", 0, startState()));
        tos = 0;

        /* continue until we are told to stop */
        for (_done_parsing = false; !_done_parsing;) {
            /* Check current token for freshness. */
            if (cur_token.used_by_parser)
                throw new Exception("TheSymbolDraft recycling detected (fix your scanner).");

            /* current state is always on the Peek of the stack */
            // debug_stack();

            /* look up actionPart @out of the current state with the current input */
            act = getAction(stack.Peek().parse_state, cur_token.symbolCount);

            /* decode the actionPart -- > 0 encodes Shift */
            if (act > 0) {
                /* Shift to the encoded state by pushing it on the stack */
                cur_token.parse_state = act - 1;
                cur_token.used_by_parser = true;
                debugShift(cur_token);
                stack.Push(cur_token);
                tos++;

                /* advance to the next TheSymbolDraft */
                cur_token = scan();
                debugMessage("# Current token is " + cur_token);
            }
            /* if its less than zero, then it encodes a reduce actionPart */
            else if (act < 0) {
                /* perform the actionPart for the reduce */
                lhs_sym = doAction((-act) - 1, this, stack, tos);

                /* look up information about the production */
                lhs_sym_num = production_tab[(-act) - 1][0];
                handle_size = production_tab[(-act) - 1][1];

                debugReduce((-act) - 1, lhs_sym_num, handle_size);

                /* Pop the handle off the stack */
                for (int i = 0; i < handle_size; i++) {
                    stack.Pop();
                    tos--;
                }

                /* look up the state to go to from the one popped back to */
                act = getReduce(stack.Peek().parse_state, lhs_sym_num);
                debugMessage(
                    "# Reduce rule: Peek state " + stack.Peek().parse_state + ", lhs symbolCount " + lhs_sym_num + " -> state " + act);

                /* Shift to that state */
                lhs_sym.parse_state = act;
                lhs_sym.used_by_parser = true;
                stack.Push(lhs_sym);
                tos++;

                debugMessage("# Goto state #" + act);
            }
            /* finally if the entry is zero, we have an error */
            else if (act == 0) {
                /* call user syntax error reporting routine */
                syntaxError(cur_token);

                /* try to error recover */
                if (!errorRecovery(true)) {
                    /* if that fails give up with a fatal syntax error */
                    unrecoveredSyntaxError(cur_token);

                    /* just in case that wasn't fatal enough, end parse */
                    doneParsing();
                }
                else {
                    lhs_sym = stack.Peek();
                }
            }
        }
        return lhs_sym;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */
    /* ExceptionXml recovery code */
    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Attempt to recover from a syntax error. This returns false if recovery fails,
     * true if it succeeds. Recovery happens in 4 steps. First we Pop the parse
     * stack down to a point at which we have a Shift @out of the Peek-most state on
     * the error TheSymbolDraft. This represents the initial error recovery configuration.
     * If no such configuration is found, then we fail. Next a small Count of
     * "lookahead" or "parse ahead" Symbols are read into a buffer. The Count of this
     * buffer is determined by error_sync_size() and determines how many Symbols
     * beyond the error must be matched to consider the recovery a success. Next, we
     * begin to discard Symbols in attempt to get past the point of error to a point
     * where we can continue parsing. After each TheSymbolDraft, we attempt to "parse ahead"
     * though the buffered lookahead Symbols. The "parse ahead" process simulates
     * that actual parse, but does not modify the real CUPParser's configuration, nor
     * execute any actions. If we can parse AllVns the stored Symbols without error,
     * then the recovery is considered a success. Once a successful recovery point
     * is determined, we do an actual parse over the stored input -- modifying the
     * real parse configuration and executing AllVns actions. Finally, we return the
     * the normal CUPParser to continue with the overall parse.
     *
     * @param debug should we produce debugging messages as we parse.
     */
    public bool errorRecovery(bool debug) /*throws java.lang.ExceptionXml*/ {
        if (debug)
            debugMessage("# Attempting error recovery");

        /*
         * first Pop the stack back into a state that can Shift on error and do that
         * Shift (if that fails, we fail)
         */
        if (!findRecoveryConfig(debug)) {
            if (debug)
                debugMessage("# ExceptionXml recovery fails");
            return false;
        }

        /* read ahead to create lookahead we can parse multiple times */
        readLookahead();

        /* repeatedly try to parse forward until we make it the required dist */
        for (; ; ) {
            /* try to parse forward, if it makes it, bail @out of loop */
            if (debug)
                debugMessage("# Trying to parse ahead");
            if (tryParseAhead(debug)) {
                break;
            }

            /* if we are now at EOF, we have failed */
            if (lookahead[0].symbolCount == EOFSym()) {
                if (debug)
                    debugMessage("# ExceptionXml recovery fails at EOF");
                return false;
            }

            /* otherwise, we consume another TheSymbolDraft and try again */
            // BUG FIX by Bruce Hutton
            // Computer Science Department, University of Auckland,
            // Auckland, New Zealand.
            // It is the first token that is being consumed, not the one
            // we were up to parsing
            if (debug)
                debugMessage("# Consuming TheSymbolDraft #" + lookahead[0].symbolCount);
            restartLookahead();
        }

        /* we have consumed to a point where we can parse forward */
        if (debug)
            debugMessage("# Parse-ahead ok, going back to normal parse");

        /* do the real parse (including actions) across the lookahead */
        parseLookahead(debug);

        /* we have success */
        return true;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Determine if we can Shift under the special error TheSymbolDraft @out of the state
     * currently on the Peek of the (real) parse stack.
     */
    public bool shiftUnderError() {
        /* is there a Shift under error TheSymbolDraft */
        return getAction(stack.Peek().parse_state, errorSym()) > 0;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Put the (real) parse stack into error recovery configuration by popping the
     * stack down to a state that can Shift on the special error TheSymbolDraft, then doing
     * the Shift. If no suitable state exists on the stack we return false
     *
     * @param debug should we produce debugging messages as we parse.
     */
    public bool findRecoveryConfig(bool debug) {
        Node error_token;
        int act;

        if (debug)
            debugMessage("# Finding recovery state on stack");

        /* Remember the _right-position of the Peek SymbolDraft on the stack */
        Node right = stack.Peek();// TUM 20060327 removed ._right
        Node left = right;// TUM 20060327 removed ._left

        /* Pop down until we can Shift under error TheSymbolDraft */
        while (!shiftUnderError()) {
            /* Pop the stack */
            if (debug)
                debugMessage("# Pop stack by one, state was # " + stack.Peek().parse_state);
            left = stack.Pop(); // TUM 20060327 removed ._left
            tos--;

            /* if we have hit bottom, we fail */
            if (stack.Count == 0) {
                if (debug)
                    debugMessage("# No recovery state found on stack");
                return false;
            }
        }

        /* state on Peek of the stack can Shift under error, find the Shift */
        act = getAction(stack.Peek().parse_state, errorSym());
        if (debug) {
            debugMessage("# Recover state found (#" + stack.Peek().parse_state + ")");
            debugMessage("# Shifting on error to state #" + (act - 1));
        }

        /* build and Shift a special error TheSymbolDraft */
        error_token = SymbolFactory.newSymbol("ERROR", errorSym(), left, right);
        error_token.parse_state = act - 1;
        error_token.used_by_parser = true;
        stack.Push(error_token);
        tos++;

        return true;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** LookAheads Symbols used for attempting error recovery "parse aheads". */
    public Node[] lookahead;

    /** Position in lookahead input buffer used for "parse ahead". */
    public int lookahead_pos;

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Read from input to establish our buffer of "parse ahead" lookahead Symbols.
     */
    public void readLookahead() /*throws java.lang.ExceptionXml*/ {
        /* create the lookahead array */
        lookahead = new Node[errorSyncSize];

        /* fill in the array */
        for (int i = 0; i < errorSyncSize; i++) {
            lookahead[i] = cur_token;
            cur_token = scan();
        }

        /* start at the beginning */
        lookahead_pos = 0;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /** Return the current lookahead in our error "parse ahead" buffer. */
    public Node curErrToken() {
        return lookahead[lookahead_pos];
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Advance to next "parse ahead" input TheSymbolDraft. Return true if we have input to
     * advance to, false otherwise.
     */
    public bool advanceLookahead() {
        /* advance the input location */
        lookahead_pos++;

        /* return true if we didn't go off the end */
        return lookahead_pos < errorSyncSize;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Reset the parse ahead input to one TheSymbolDraft past where we started error
     * recovery (this consumes one new TheSymbolDraft from the real input).
     */
    public void restartLookahead() /*throws java.lang.ExceptionXml*/ {
        /* move AllVns the existing input over */
        for (int i = 1; i < errorSyncSize; i++)
            lookahead[i - 1] = lookahead[i];

        /* read a new TheSymbolDraft into the last spot */
        // BUG Fix by Bruce Hutton
        // Computer Science Department, University of Auckland,
        // Auckland, New Zealand. [applied 5-sep-1999 by csa]
        // The following two lines were @out of order!!
        lookahead[errorSyncSize - 1] = cur_token;
        cur_token = scan();

        /* reset our internal position marker */
        lookahead_pos = 0;
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Do a simulated parse forward (a "parse ahead") from the current stack
     * configuration using stored lookahead input and a virtual parse stack. Return
     * true if we make it AllVns the way through the stored lookahead input without
     * error. This basically simulates the actionPart of parse() using only our saved
     * "parse ahead" input, and not executing any actions.
     *
     * @param debug should we produce debugging messages as we parse.
     */
    public bool tryParseAhead(bool debug) /*throws java.lang.ExceptionXml*/ {
        int act;
        short lhs, rhs_size;

        /* create a virtual stack from the real parse stack */
        VirtualParseStack vstack = new VirtualParseStack(stack);

        /* parse until we fail or get past the lookahead input */
        for (; ; ) {
            /* look up the actionPart from the current state (on Peek of stack) */
            act = getAction(vstack.Peek(), curErrToken().symbolCount);

            /* if its an error, we fail */
            if (act == 0)
                return false;

            /* > 0 encodes a Shift */
            if (act > 0) {
                /* Push the new state on the stack */
                vstack.Push(act - 1);

                if (debug)
                    debugMessage("# Parse-ahead shifts TheSymbolDraft #" + curErrToken().symbolCount + " into state #" + (act - 1));

                /* advance simulated input, if we run off the end, we are done */
                if (!advanceLookahead())
                    return true;
            }
            /* < 0 encodes a reduce */
            else {
                /* if this is a reduce with the start production we are done */
                if ((-act) - 1 == startProduction()) {
                    if (debug)
                        debugMessage("# Parse-ahead accepts");
                    return true;
                }

                /* get the lhs TheSymbolDraft and the rhs Count */
                lhs = production_tab[(-act) - 1][0];
                rhs_size = production_tab[(-act) - 1][1];

                /* Pop handle off the stack */
                for (int i = 0; i < rhs_size; i++)
                    vstack.Pop();

                if (debug)
                    debugMessage(
                        "# Parse-ahead reduces: handle Count = " + rhs_size + " lhs = #" + lhs + " from state #" + vstack.Peek());

                /* look up goto and Push it onto the stack */
                vstack.Push(getReduce(vstack.Peek(), lhs));
                if (debug)
                    debugMessage("# Goto state #" + vstack.Peek());
            }
        }
    }

    /* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */

    /**
     * Parse forward using stored lookahead Symbols. In this case we have already
     * verified that parsing will make it through the stored lookahead Symbols and
     * we are now getting back to the point at which we can hand control back to the
     * normal CUPParser. Consequently, this version of the CUPParser performs AllVns actions
     * and modifies the real parse configuration. This returns once we have consumed
     * AllVns the stored input or we accept.
     *
     * @param debug should we produce debugging messages as we parse.
     */
    public void parseLookahead(bool debug) /*throws java.lang.ExceptionXml*/ {
        /* the current actionPart code */
        int act;

        /* the TheSymbolDraft/stack element returned by a reduce */
        Node lhs_sym = null;

        /* information about production being reduced with */
        short handle_size, lhs_sym_num;

        /* restart the saved input at the beginning */
        lookahead_pos = 0;

        if (debug) {
            debugMessage("# Reparsing saved input with actions");
            debugMessage("# Current TheSymbolDraft is #" + curErrToken().symbolCount);
            debugMessage("# Current state is #" + stack.Peek().parse_state);
        }

        /* continue until we accept or have read AllVns lookahead input */
        while (!_done_parsing) {
            /* current state is always on the Peek of the stack */

            /* look up actionPart @out of the current state with the current input */
            act = getAction(stack.Peek().parse_state, curErrToken().symbolCount);

            /* decode the actionPart -- > 0 encodes Shift */
            if (act > 0) {
                /* Shift to the encoded state by pushing it on the stack */
                curErrToken().parse_state = act - 1;
                curErrToken().used_by_parser = true;
                if (debug)
                    debugShift(curErrToken());
                stack.Push(curErrToken());
                tos++;

                /* advance to the next TheSymbolDraft, if there is none, we are done */
                if (!advanceLookahead()) {
                    if (debug)
                        debugMessage("# Completed reparse");

                    /* scan next TheSymbolDraft so we can continue parse */
                    // BUGFIX by Chris Harris <ckharris@ucsd.edu>:
                    // correct a one-off error by commenting @out
                    // this next line.
                    /* cur_token = scan(); */

                    /* go back to normal CUPParser */
                    return;
                }

                if (debug)
                    debugMessage("# Current TheSymbolDraft is #" + curErrToken().symbolCount);
            }
            /* if its less than zero, then it encodes a reduce actionPart */
            else if (act < 0) {
                /* perform the actionPart for the reduce */
                lhs_sym = doAction((-act) - 1, this, stack, tos);

                /* look up information about the production */
                lhs_sym_num = production_tab[(-act) - 1][0];
                handle_size = production_tab[(-act) - 1][1];

                if (debug)
                    debugReduce((-act) - 1, lhs_sym_num, handle_size);

                /* Pop the handle off the stack */
                for (int i = 0; i < handle_size; i++) {
                    stack.Pop();
                    tos--;
                }

                /* look up the state to go to from the one popped back to */
                act = getReduce(stack.Peek().parse_state, lhs_sym_num);

                /* Shift to that state */
                lhs_sym.parse_state = act;
                lhs_sym.used_by_parser = true;
                stack.Push(lhs_sym);
                tos++;

                if (debug)
                    debugMessage("# Goto state #" + act);

            }
            /*
             * finally if the entry is zero, we have an error (shouldn't happen here,
             * but...)
             */
            else if (act == 0) {
                reportFatalError("Syntax error", lhs_sym);
                return;
            }
        }

    }

    /*-----------------------------------------------------------*/

    /** Utility function: unpacks parse tables from strings */
    public static short[][] unpackFromStrings(String[] sa) {
        // Concatanate initialization strings.
        StringBuilder sb = new StringBuilder(sa[0]);
        for (int i = 1; i < sa.Length; i++)
            sb.Append(sa[i]);
        int n = 0; // location in initialization string
        int size1 = (((int)sb[n]) << 16) | ((int)sb[n + 1]);
        n += 2;
        short[][] result = new short[size1][];
        for (int i = 0; i < size1; i++) {
            int size2 = (((int)sb[n]) << 16) | ((int)sb[n + 1]);
            n += 2;
            result[i] = new short[size2];
            for (int j = 0; j < size2; j++)
                result[i][j] = (short)(sb[n++] - 2);
        }
        return result;
    }
}
